package org.ariadne_eu.hcifetcher.servlet;

import java.io.IOException;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.swing.text.DateFormatter;

import org.joda.time.DateTimeZone;
import org.joda.time.format.DateTimeFormat;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.Key;
public class AddTodoItemServlet extends HttpServlet{
	
	private static final long serialVersionUID = 1L;
	private static final Logger log = Logger.getLogger(AddTodoItemServlet.class.getName());
	
	@Override
	public void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		String student = req.getParameter("studentid");
		String itemid = req.getParameter("itemid");
		String deadline = req.getParameter("deadline");
		String description = req.getParameter("description");
		DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
		Entity todoItem = new Entity("TodoItem");
		todoItem.setProperty("studentid", student);
		todoItem.setProperty("itemid", itemid);
		resp.getWriter().write("Please store dates in the dd-MM-YYYY HH:mm:ss (ex. 25-12-2011 15:40:57) format!)\n");
		//resp.getWriter().write(DateTimeFormat.forPattern("dd-MM-YYYY HH:mm:ss").withZone(DateTimeZone.forOffsetHours(1)).print(dateTime));
		Date deadlinedate = DateTimeFormat.forPattern("dd-MM-YYYY HH:mm:ss").withZone(DateTimeZone.forOffsetHours(1)).parseDateTime(deadline).toDate();
		todoItem.setProperty("deadline", deadlinedate);
		todoItem.setProperty("datestamp", new Date());
		todoItem.setProperty("description", description);
		Key k = datastore.put(todoItem);
		resp.getWriter().write("Added todo by " + student + " of item with ID: " + itemid + ". Deadline: " + deadline + " Description:" + description + ". Key:" + k);
		log.log(Level.INFO, "Added todo by " + student + " of item with ID: " + itemid + ". Deadline: " + deadline + " Description:" + description + ". Key: " + k);
	}
	
	@Override
	public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		doPost(req,resp);
	}


}
